import React, { useEffect, useRef, useState, useCallback } from "react";
import BScroll from "@better-scroll/core";
import utils from "@/tools/yh";
const Scroll = props => {
	const { children, isRefresh, isScroll, getBs, onScroll, ..._props } = props;
	const [bs, setBs] = useState();
	const ref = useRef(null);
	const initScroll = useCallback(() => {
		if (ref.current) {
			const bs = new BScroll(ref.current, {
				scrollX: true,
				click: true,
				scrollY: true,
				probeType: 3
			});

			if (onScroll) {
				if (getBs) {
					getBs(bs);
				}
				bs.on(
					"scroll",
					utils.throttle(() => {
						onScroll(bs);
					}, 1000)
				);
			}

			setBs(bs);
		}
	});
	useEffect(() => {
		initScroll();
		window.addEventListener("hashchange", initScroll);
		return () => {
			window.removeEventListener("hashchange", initScroll);
		};
	}, [ref]);

	useEffect(() => {
		if (bs) {
			setTimeout(() => bs.refresh(), 16);
		}
	}, [isRefresh]);
	if (isScroll) {
		return (
			<div
				ref={ref}
				style={{
					height: "100%",
					overflow: "hidden",
					position: "relative"
				}}
				{..._props}
			>
				{children}
			</div>
		);
	}
	return children;
};

export default Scroll;
